package com.hdl.config;

import com.hdl.io.Resources;
import com.hdl.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author hedonglin
 * @date 2020/4/21 21:06
 * @description
 */
public class XmlConfigBuilder {
    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是讲配置文件进行解析，封装成Configuration
     */
    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(in);

        // <configuration>
        Element rootElement = document.getRootElement();

        List<Element> list = rootElement.selectNodes("//properties");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

        XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
        // mapper解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }

}
